package com.jahe.learn.netty4.zerocopy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * nio的机制传送文件数据，性能是老式io的近 6倍以上
 * @author: jahe.lai
 * @create: 2019-12-25 20:26
 */
public class NIOFileClient {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(true);
//        Selector selector = Selector.open();
//        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8899));

        String filename = "D:/softs/ideaIU-2019.2.4.win.zip";
        long st = System.currentTimeMillis();

        FileChannel channel = new FileInputStream(filename).getChannel();

        // 很多操作系统会在底层直接将文件系统的内容，直接拷贝到设备的传输缓存 中。
        long transferCount = channel.transferTo(0, channel.size(), socketChannel);

        System.out.println("发送总字节数：" + transferCount + ", 耗时(ms)：" + (System.currentTimeMillis() - st));
        channel.close();
//        socketChannel.close();
    }
}
